﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace VTFC
{
    // ----------------------------------------------------------------------------
    /// <summary>
    /// Tasks form.
    /// </summary>
    // ----------------------------------------------------------------------------
    public partial class FrmTaskList : Form
    {
        /// <summary><see cref="VTFC.Task"/> collection.</summary>
        private List<Task> Tasks { get; set; }                
        /// <summary><see cref="System.EventHandler"/> to write message in output control on form FrmMain</summary>
        public event WriteOutputEvent WriteOutput;

        // ----------------------------------------------------------------------------
        /// <summary>
        /// Constructor.
        /// </summary>
        // ----------------------------------------------------------------------------
        public FrmTaskList()
        {
            InitializeComponent();
            InitializeContent();
        }//ctor

        private void InitializeContent()
        {
            this.Text = Resources.FrmTaskList_Text;
            colFile.Text = Resources.FrmTaskList_colFile;
            colSize.Text = Resources.FrmTaskList_colSize;
            colTaskType.Text = Resources.FrmTaskList_colTaskType;
            btnCancel.Text = Resources.ButtonCancel;
            btnOk.Text = Resources.ButtonOk;
        }//func InitializeContent
                
        private void FrmTaskList_Load(object sender, EventArgs e)
        {
            this.Text = Connector.Server.Url + " - " + Resources.TaskListTitle;
            pbTask.Style = ProgressBarStyle.Marquee;            
            bgwGetTaskList.RunWorkerAsync();
        }//func FrmTaskList_Load

        #region GetTaskList
        private void bgwGetTaskList_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = Connector.GetTaskList();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex);
                BaseLogic.ShowError(ex);
            }
        }//func bgwGetTaskList_DoWork

        private void bgwGetTaskList_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }//func bgwGetTaskList_ProgressChanged

        private void bgwGetTaskList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool close = false;
            List<Task> tasks = e.Result as List<Task>;
            if (tasks != null)
            {
                int taskcount = tasks.Count;
                if (taskcount > 0)
                {
                    lblAllTask.Text = taskcount.ToString();
                    if (tasks != null)
                    {
                        lvTasks.BeginUpdate();
                        lvTasks.Items.Clear();
                        foreach (Task task in tasks)
                        {
                            lvTasks.Items.Add(new ListViewItemTask()
                            {
                                Task = task,
                                Checked = GetTaskCheckState(task.TaskType),
                                ImageIndex = 0,
                            });
                        }
                        lvTasks.EndUpdate();
                    }
                    pbTask.Style = ProgressBarStyle.Blocks;
                }
                else
                {
                    close = true;
                }
            }
            else
            {
                close = true;
            }
            if (close)
            {
                this.DialogResult = DialogResult.OK;
            }
        }//func bgwGetTaskList_RunWorkerCompleted

        private bool GetTaskCheckState(TaskType type)
        {
            bool auto = true;
            if (type == TaskType.COMFIRM_THAN_UPDATE)
            {
                auto = false;
            }
            return auto;
        }//func GetTaskCheckState
                
        #endregion

        #region GetLatestVersion
        private void btnOk_Click(object sender, EventArgs e)
        {
            Tasks = new List<Task>();
            foreach (ListViewItemTask item in lvTasks.Items)
            {
                if (item.Checked)
                {
                    Tasks.Add(item.Task);
                }
                else
                {
                    item.Task.Document.Skipped = true;
                }
            }
            lblAllTask.Text = Tasks.Count.ToString();
            pbTask.Maximum = Tasks.Count;
            bgwExecuteTaskList.RunWorkerAsync();
        }//func btnOk_Click

        private void bgwExecuteTaskList_DoWork(object sender, DoWorkEventArgs e)
        {
            if (Tasks.Count > 0)
            {
                BackgroundWorker bgw = sender as BackgroundWorker;
                for (int i = 0; i < Tasks.Count; i++)
                {
                    Connector.ExecuteTask(Tasks[i]);
                    bgw.ReportProgress(i);
                }
                Connector.Content.GetLatestVersion = DateTime.Now;
            }
            Connector.SaveContent();
        }//func bgwExecuteTaskList_DoWork

        private void bgwExecuteTaskList_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
            OnWriteOutput(Tasks[e.ProgressPercentage]);
            lblCompleted.Text = e.ProgressPercentage.ToString();
            pbTask.Increment(1);
        }//func bgwExecuteTaskList_ProgressChanged

        private void bgwExecuteTaskList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {            
            this.DialogResult = DialogResult.OK;
        }//func bgwExecuteTaskList_RunWorkerCompleted
        #endregion

        private void ckbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            bool checkall = ckbCheckAll.Checked;
            foreach (ListViewItemTask item in lvTasks.Items)
            {
                item.Checked = checkall;
            }
        }//func ckbCheckAll_CheckedChanged   

        private void btnCancel_Click(object sender, EventArgs e)
        {
            CancelWorkers();
            foreach (ListViewItemTask item in lvTasks.Items)
            {
               item.Task.Document.Skipped = true;               
            }
            this.DialogResult = DialogResult.Cancel;
        }//func btnCancel_Click

        private void CancelWorkers()
        {
            if (bgwGetTaskList.IsBusy == true)
            {
                bgwGetTaskList.CancelAsync();
            }
            if (bgwExecuteTaskList.IsBusy == true)
            {
                bgwExecuteTaskList.CancelAsync();
            }
        }//func CancelWorkers

        // ----------------------------------------------------------------------------
        /// <summary>
        /// Write output delegate.
        /// </summary>
        /// <param name="sender">this instance.</param>
        /// <param name="e"><see cref="VTFC.WriteOutputEventArgs"/></param>
        // ----------------------------------------------------------------------------
        public delegate void WriteOutputEvent(object sender, WriteOutputEventArgs e);

        // ----------------------------------------------------------------------------
        /// <summary>
        /// Write message to output.
        /// </summary>
        /// <param name="task">Executed <see cref="VTFC.Task"/> incance.</param>
        // ----------------------------------------------------------------------------
        protected void OnWriteOutput(Task task)
        {
            string message = String.Format(Resources.Msg_Information_TaskExecuted, task.MetaData.FileName);
            OnWriteOutput(message);
        }//func OnWriteOutput

        // ----------------------------------------------------------------------------
        /// <summary>
        /// Write message to output.
        /// </summary>
        /// <param name="message">Message to output</param>
        // ----------------------------------------------------------------------------
        protected void OnWriteOutput( string message )
        {
            if (WriteOutput != null)
            {
                WriteOutput(this, new WriteOutputEventArgs(message));
            }
        }//func OnWriteOutput
    }//class FrmTaskList
}//namespace VTFC
